package com.liu.email;

import sun.misc.BASE64Decoder;

import java.io.*;

public class Base64Decoder {
    public static void main(String[] args) throws IOException {
        String fileCatalog = "C:\\Users\\ydxx\\Desktop\\MailContent";
        String smtpId = "123321";
//		String fileName = "";
        String[] fileNames = {"转发.txt", "imagejpg_B_1.txt", "imagejpg_B_2.txt"};
        // String[] fileNames = {"转发.txt","textHtml_UTF8_B.txt"};
        Base64DataDecoderForText(fileCatalog, smtpId, fileNames);
    }

    /**
     * 附件解码及下载
     */
    public static void Base64DataDecoderForFile(String MailContentFileCatalog, String smtpId, String fileName)
            throws IOException {
        // 页面编码方式：①utf-8。②GB2312等
        String charset = "utf-8";
        // 邮件编码方式：①base64。②quoted-printable
        String contentTransferEncoding = "B";
        int beginIndex = 0;
        int endIndex = 0;
        String temp = "";
        // 转换后下载的文件名称
        String decoderFileName = "";
        // 读取邮件内容文件夹
        File smtpIdFile = new File(MailContentFileCatalog, smtpId);
        // 判断文件夹是否存在
        if (!smtpIdFile.exists()) {

        }
        File file = new File(smtpIdFile, fileName);
        // 判断文件是否存在
        if (!file.exists()) {
            System.err.println(file + "不存在");
        }
        // beginIndex = fileName.indexOf("multipart");
        beginIndex = "multipart".length();
        endIndex = fileName.indexOf("_");
        decoderFileName = fileName.substring(beginIndex, endIndex);

        temp = fileName.substring(endIndex + 1, fileName.length());
        beginIndex = temp.indexOf("_");
        endIndex = beginIndex + 1;
        charset = temp.substring(0, beginIndex).toLowerCase();
        contentTransferEncoding = temp.substring(endIndex, endIndex + 1).toUpperCase();

        File outFile = new File("\\C:\\Users\\ydxx\\Desktop", decoderFileName);
        if (outFile.exists()) { // 如果已存在,删除旧文件
            outFile.delete();
        }
        outFile = new File("\\C:\\Users\\ydxx\\Desktop", decoderFileName);
        outFile.createNewFile();

        FileInputStream fileInStream = new FileInputStream(file);
        if ("B".equals(contentTransferEncoding)) {
            try {
                byte[] buffer = new BASE64Decoder().decodeBuffer(fileInStream);
                ByteArrayInputStream byteInputStream = new ByteArrayInputStream(buffer);
                BufferedInputStream bis = new BufferedInputStream(byteInputStream);
                FileOutputStream out = new FileOutputStream(outFile);
                BufferedOutputStream bos = new BufferedOutputStream(out);

                byte[] bytes = new byte[1024];
                int length = bis.read(bytes);
                while (length != -1) {
                    bos.write(bytes, 0, length);
                    length = bis.read(bytes);
                }
                out.close();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 邮件正文读取 1：文字 2：图片 3:HTML排版
     *
     * @param MailContentFileCatalog                                             \\C:\\Users\\ydxx\\Desktop\\MailContent
     * @param smtpId                                                             123321
     * @param textHtml_页面编码方式_B/Q_顺序号;textPlain_页面编码方式_B/Q_顺序号;imageXxx_B/Q_顺序号;
     * @throws IOException
     */
    public static StringBuffer Base64DataDecoderForText(String MailContentFileCatalog, String smtpId, String[] fileName)
            throws IOException {
        // 页面编码方式：①utf-8。②GB2312等
        String charset = "utf-8";
        // 邮件编码方式：①base64。②quoted-printable
        String contentTransferEncoding = "B";
        StringBuffer html = new StringBuffer();
        html.append("<!DOCTYPE html><html><head><meta charset='UTF-8'></head><body><div><span><pre>");
        byte[] buffer = null;
        String body = null;
        int beginIndex = 0;
        int endIndex = 0;
        String imageType = "";
        InputStreamReader reader = null;
        // 读取邮件内容文件夹
        File smtpIdFile = new File(MailContentFileCatalog, "textHtml.txt");
        // 判断文件夹是否存在
        if (!smtpIdFile.exists()) {
            System.err.println(MailContentFileCatalog + "不存在" + smtpId);
        }
        for (int i = 0; i < fileName.length; i++) {
            File file = new File(smtpIdFile, fileName[i]);
            System.out.println(smtpIdFile + fileName[i] + "文件大小：" + file.length());
            // 判断文件是否存在
            if (!file.exists()) {
                System.err.println(smtpId + "不存在" + file);
            }
            FileInputStream fileInStream = new FileInputStream(file);

            if ("B".equals(contentTransferEncoding)) {
                try {
                    if (fileName[i].startsWith("image")) {// 正文图片
                        beginIndex = "image".length();
                        endIndex = fileName[i].indexOf("_");
                        imageType = fileName[i].substring(beginIndex, endIndex);
                        Long length = file.length();
                        char[] imgChars = new char[length.intValue()];
                        int charread = 0;
                        StringBuffer buffers = new StringBuffer();
                        reader = new InputStreamReader(fileInStream);
                        while ((charread = reader.read(imgChars)) != -1) {
                            if ((charread == imgChars.length) && (imgChars[imgChars.length - 1] != '\r')) {
                                buffers.append(imgChars);
                            } else {
                                for (int j = 0; j < charread; j++) {
                                    if (imgChars[j] == '\r') {
                                        continue;
                                    } else {
                                        buffers.append(imgChars[j]);
                                    }
                                }
                            }
                        }
                        body = "<img src='data:image/" + imageType + ";base64," + buffers + "'/>";
                    } else if (fileName[i].startsWith("textHtml")) {// 正文格式
                        buffer = new BASE64Decoder().decodeBuffer(fileInStream);
                        body = new String(buffer, charset);
                    } else {// 正文內容
                        buffer = new BASE64Decoder().decodeBuffer(fileInStream);
                        body = new String(buffer, charset).replace("<", "<");
                    }
                    html.append(body);
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                } finally {
                    if (reader != null)
                        reader.close();
                }
            }
        }
        html.append("</pre></span></div></body></html>");

        // 测试文件解码是否正确,完成测试后下面需要注释掉
        File outFile = new File("\\C:\\Users\\ydxx\\Desktop", "demo.html");
        if (outFile.exists()) { // 如果已存在,删除旧文件
            outFile.delete();
        }
        outFile = new File("\\C:\\Users\\ydxx\\Desktop", "demo.html");
        outFile.createNewFile();
        FileOutputStream out = new FileOutputStream(outFile);
        out.write(html.toString().getBytes(charset));
        out.close();
        // 测试结束
        return html;
    }

    // public static void Base64DataDecoderForFile(String
    // MailContentFileCatalog, String smtpId, String fileName)
    // throws IOException {
    // int beginIndex = 0;
    // int endIndex = 0;
    // String temp = "";
    // // 转换后下载的文件名称
    // String decoderFileName = "";
    // // 页面编码方式：①utf-8。②GB2312等
    // String charset = "";
    // // 邮件编码方式：①base64。②quoted-printable
    // String contentTransferEncoding = "";
    // // 读取邮件内容文件夹
    // File smtpIdFile = new File(MailContentFileCatalog, smtpId);
    // // 判断文件夹是否存在
    // if (!smtpIdFile.exists()) {
    // System.err.println(MailContentFileCatalog + "不存在" + smtpId + "文件夹");
    // }
    // File file = new File(smtpIdFile, fileName);
    // // 判断文件是否存在
    // if (!file.exists()) {
    // System.err.println(file + "不存在");
    // }
    // // beginIndex = fileName.indexOf("multipart");
    // beginIndex = "multipart".length();
    // endIndex = fileName.indexOf("_");
    // decoderFileName = fileName.substring(beginIndex, endIndex);
    //
    // temp = fileName.substring(endIndex + 1, fileName.length());
    // beginIndex = temp.indexOf("_");
    // endIndex = beginIndex + 1;
    // charset = temp.substring(0, beginIndex).toLowerCase();
    // contentTransferEncoding = temp.substring(endIndex, endIndex +
    // 1).toLowerCase();
    //
    // File outFile = new File("\\C:\\Users\\ydxx\\Desktop", decoderFileName);
    // if (outFile.exists()) { // 如果已存在,删除旧文件
    // outFile.delete();
    // }
    // outFile = new File("\\C:\\Users\\ydxx\\Desktop", decoderFileName);
    // outFile.createNewFile();
    //
    // FileInputStream fileInStream = new FileInputStream(file);
    // if ("b".equals(contentTransferEncoding)) {
    // try {
    // byte[] buffer = new BASE64Decoder().decodeBuffer(fileInStream);
    // FileOutputStream out = new FileOutputStream(outFile);
    // out.write(buffer);
    // out.close();
    // } catch (UnsupportedEncodingException e) {
    // e.printStackTrace();
    // }
    // }
    // }
    // public String Base64DataDecoderForFile(String base64Data, String charset,
    // String contentTransferEncoding,
    // String fileName) throws IOException {
    // String text = "";
    // // String fileType = fileName.substring(fileName.lastIndexOf("."));
    // if ("B".equals(contentTransferEncoding) ||
    // "base64".equals(contentTransferEncoding)) {
    //
    // File file = new File(file, fileName);
    // try {
    // byte[] buffer = new BASE64Decoder().decodeBuffer(base64Data);
    // FileOutputStream out = new FileOutputStream(file);
    // out.write(buffer);
    // out.close();
    // } catch (UnsupportedEncodingException e) {
    // e.printStackTrace();
    // }
    // }
    // return text;
    // }

}
